package zb.blog.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zb.blog.base.bean.Result;
import zb.blog.base.global.GlobalVar;
import zb.blog.bean.NavBarBean;
import zb.blog.dao.NavBarDao;
import zb.blog.service.INavBarService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class NavBarService implements INavBarService {
    @Autowired
    private NavBarDao navBarDao;

    @Override
    public List<Map<String, Object>> getNavBarByEnable(Integer enable) {
        List<NavBarBean> navBarList = navBarDao.getNavBar(enable);
        List<Map<String, Object>> treeMenuList = this.ListNavBarToTree(navBarList);
        return treeMenuList;
    }

    @Override
    public Result updateStatus(Integer status, Integer id) {
        Result res = new Result();
        if (status == null || id == null) {
            res.setMsg("参数错误！");
            res.setSuccess(GlobalVar.FAIL);
            return res;
        }
        try {
            navBarDao.updateStatus(status, id);
            res.setMsg("状态更新成功！");
            res.setSuccess(GlobalVar.SUCCESS);
            return res;
        } catch (Exception e) {
            res.setMsg("状态更新失败！");
            res.setSuccess(GlobalVar.FAIL);
            return res;
        }
    }

    @Override
    public List<Map<String, Object>> getNavBarToZtree(Integer status) {
        return navBarDao.getNavBarToZtree(status);
    }

    public List<Map<String, Object>> ListNavBarToTree(List<NavBarBean> navBarList) {
        List<Map<String, Object>> treeMenuList = new ArrayList<>();
        List<NavBarBean> parentList = navBarList.stream().filter((x) -> x.getParent_id() == 0).collect(Collectors.toList());
        for (NavBarBean navBarBean : parentList) {
            Map<String, Object> treeMap = new HashMap<>();
            int id = navBarBean.getId();
            List<NavBarBean> subMenuList = navBarList.stream().filter((x) -> x.getParent_id() == id).collect(Collectors.toList());
            treeMap.put("parentMenu", navBarBean);
            treeMap.put("subMenu", subMenuList);
            treeMenuList.add(treeMap);
        }
        return treeMenuList;
    }
}
